package util;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;
/**
 * @Author:zhengbowen
 * @Date: 2025/09/07 16:04
 * @Description:键盘监听配置类
 */
public class KeyStatesConfig {
    private static final Map<Integer, Boolean> keyStates = new HashMap<>();
    private static JComponent targetComponent = null;

    public KeyStatesConfig(JComponent component) {
        targetComponent = component;
        bindWASDKeys();
    }

    // 封装单个按键绑定
    private static void bindKey(int keyCode, String keyName) {
        InputMap inputMap = targetComponent.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        ActionMap actionMap = targetComponent.getActionMap();

        // 按下事件
        inputMap.put(KeyStroke.getKeyStroke(keyCode, 0, false), keyName + "Pressed");
        actionMap.put(keyName + "Pressed", new AbstractAction() {
            @Override public void actionPerformed(ActionEvent e) {
                keyStates.put(keyCode, true);
            }
        });

        // 释放事件
        inputMap.put(KeyStroke.getKeyStroke(keyCode, 0, true), keyName + "Released");
        actionMap.put(keyName + "Released", new AbstractAction() {
            @Override public void actionPerformed(ActionEvent e) {
                keyStates.put(keyCode, false);
            }
        });
    }

    // 批量绑定常用按键
    public void bindWASDKeys() {
        bindKey(KeyEvent.VK_W, "w");
        bindKey(KeyEvent.VK_A, "a");
        bindKey(KeyEvent.VK_S, "s");
        bindKey(KeyEvent.VK_D, "d");
        bindKey(KeyEvent.VK_R, "r");
        bindKey(KeyEvent.VK_LEFT, "left");
        bindKey(KeyEvent.VK_RIGHT, "right");
        bindKey(KeyEvent.VK_UP, "up");
        bindKey(KeyEvent.VK_DOWN, "down");
        bindKey(KeyEvent.VK_J, "j");
        bindKey(KeyEvent.VK_SPACE, " ");
    }

    // 检查按键状态
    public static boolean isKeyPressed(int keyCode) {
        return keyStates.getOrDefault(keyCode, false);
    }

    // 获取所有按键状态
    public static Map<Integer, Boolean> getKeyStates() {
        return new HashMap<>(keyStates);
    }
}
